package com.haixiaoke.saas.house.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.haixiaoke.saas.common.Node;
import com.haixiaoke.saas.common.exception.ServiceException;
import com.haixiaoke.saas.common.tenant.TenantContext;
import com.haixiaoke.saas.common.utils.DateUtils;
import com.haixiaoke.saas.common.utils.StringUtils;
import com.haixiaoke.saas.house.domain.Building;
import com.haixiaoke.saas.house.domain.Estate;
import com.haixiaoke.saas.house.domain.Unit;
import com.haixiaoke.saas.house.mapper.BuildingMapper;
import com.haixiaoke.saas.house.service.IBuildingService;
import com.haixiaoke.saas.house.service.IEstateService;
import com.haixiaoke.saas.house.service.IHouseService;
import com.haixiaoke.saas.house.service.IUnitService;
import com.haixiaoke.saas.system.framework.security.util.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * 楼栋信息Service业务层处理
 *
 * @author xiaolong
 * @date 2023-10-16
 */
@Service
public class BuildingServiceImpl implements IBuildingService {
    @Autowired
    private BuildingMapper buildingMapper;
    @Autowired
    private IUnitService iUnitService;
    @Autowired
    private IHouseService iHouseService;
    @Autowired
    private IEstateService iEstateService;

    /**
     * 查询楼栋信息
     *
     * @param buildingId 楼栋信息主键
     * @return 楼栋信息
     */
    @Override
    public Building selectBuildingByBuildingId(String buildingId) {
        Building building = buildingMapper.selectBuildingByBuildingId(buildingId);
        Unit unit = new Unit();
        unit.setBuildingId(buildingId);
        List<Unit> unitList = iUnitService.selectUnitList(unit);
        building.setUnitList(unitList);
        return building;
    }

    /**
     * 查询楼栋信息列表
     *
     * @param building 楼栋信息
     * @return 楼栋信息
     */
    @Override
    public List<Building> selectBuildingList(Building building) {
        return buildingMapper.selectBuildingList(building);
    }

    /**
     * 新增楼栋信息
     *
     * @param building 楼栋信息
     * @param userId
     * @return 结果
     */
    @Override
    @Transactional
    public int insertBuilding(Building building, Long userId) {
        if (building.getBuildingName().length() > 10) {
            throw new ServiceException("楼栋名称不能超过10个字");
        }

        Building sqlBuilding = buildingMapper.selectBuildingByEstateIdAndBuildingName(building.getEstateId(), building.getBuildingName(), null);
        if (ObjectUtil.isNotEmpty(sqlBuilding)) {
            throw new ServiceException("该楼栋名称已存在");
        }

        List<Unit> unitList = building.getUnitList();
        if (CollectionUtil.isEmpty(unitList)) {
            throw new ServiceException("单元信息不能为空");
        }

        Estate estate = iEstateService.selectEstateByEstateId(building.getEstateId());
        if (ObjectUtil.isNotEmpty(estate)) {
            building.setEstateType(estate.getEstateType());
            building.setPremisesAddress(estate.getPremisesAddress());
            building.setPropertyId(estate.getPropertyId());
            building.setPropertyName(estate.getPropertyName());

            // 2024-2-26 修改为从楼盘获取位置信息
            building.setProvinceId(estate.getProvinceId());
            building.setCityId(estate.getCityId());
            building.setDistrictId(estate.getDistrictId());
            building.setStreetId(estate.getStreetId());
            building.setCommunityId(estate.getCommunityId());
        }
        building.setOperatorId(userId);
        building.setCreateTime(DateUtils.getNowDate());
        buildingMapper.insertBuilding(building);


        for (Unit unit : unitList) {
            Unit sqlUnit = iUnitService.selectUnitByUnitBuildingAndUnitName(building.getBuildingId(), unit.getUnitName());
            if (ObjectUtil.isNotEmpty(sqlUnit)) {
                throw new ServiceException(unit.getUnitName() + "单元名称已存在");
            }
            unit.setOperatorId(userId);
            unit.setBuildingId(building.getBuildingId());
            unit.setCreateTime(DateUtils.getNowDate());
            unit.setTenantId(TenantContext.getTenantId());
            iUnitService.insertUnit(unit);
        }

        return 1;
    }

    /**
     * 修改楼栋信息
     * @param building 楼栋信息
     * @return 结果
     */
    @Override
    public int updateBuilding(Building building) {
        building.setUpdateTime(DateUtils.getNowDate());
        return buildingMapper.updateBuilding(building);
    }

    /**
     * 批量删除楼栋信息
     *
     * @param buildingIds 需要删除的楼栋信息主键
     * @return 结果
     */
    @Override
    @Transactional
    public int deleteBuildingByBuildingIds(String[] buildingIds) {
        Building newBuilding = new Building();
        newBuilding.setTenantId(TenantContext.getTenantId());
        newBuilding.setBuildingIds(buildingIds);
        List<Building> buildingList = buildingMapper.selectBuildingByBuildingIds(newBuilding);
        if (buildingList.size() < buildingIds.length) {
            return 0;
        }

        int i = 0;
        for (String buildingId : buildingIds) {
            Building building = buildingMapper.selectBuildingByBuildingId(buildingId);
            Unit unit = new Unit();
            unit.setBuildingId(buildingId);
            List<Unit> unitList = iUnitService.selectUnitList(unit);
            if (CollectionUtil.isNotEmpty(unitList)) {
                throw new ServiceException(building.getEstateName() + "楼盘-" + building.getBuildingName() + "楼栋，存在单元不可删除！");
            }
            building.setUpdateTime(DateUtils.getNowDate());
            building.setDelFlag(Building.DEL_FLAG_NO);
            buildingMapper.updateBuilding(building);
            i += 1;
        }

        return i;
    }

    /**
     * 删除楼栋信息信息
     *
     * @param buildingId 楼栋信息主键
     * @return 结果
     */
    @Override
    public int deleteBuildingByBuildingId(Long buildingId) {
        return buildingMapper.deleteBuildingByBuildingId(buildingId);
    }

    /**
     * 统计楼栋数据
     *
     * @return
     */
    @Override
    public Building getStatistics() {
        Building building = new Building();
        // 查询楼栋数量
        Integer buildingNumber = buildingMapper.selectBuildingByBuildingNumber(null, Building.DEL_FLAG_YES, TenantContext.getTenantId());
        // 查询单元数量
        Integer unitNumber = iUnitService.selectUnitByUnitNumber(null, Unit.DEL_FLAG_YES, TenantContext.getTenantId());
        // 查询房间数量
        Integer houseNumber = iHouseService.selectHouseByHouseNumber(null, null, TenantContext.getTenantId());
        building.setBuildingNumber(buildingNumber);
        building.setUnitNumber(unitNumber);
        building.setHouseNumber(houseNumber);
        return building;
    }

    @Override
    public List<Building> selectBuildingListInfo(Building building) {
        List<Building> buildingList = buildingMapper.selectBuildingList(building);
        if (CollectionUtil.isNotEmpty(buildingList)) {
            for (Building building1 : buildingList) {
                Integer unitNumber = iUnitService.selectUnitByUnitNumber(building1.getBuildingId(), Unit.DEL_FLAG_YES, TenantContext.getTenantId());
                Integer houseNumber = iHouseService.selectHouseByBuildingIdHouseNumber(building1.getBuildingId(), null, TenantContext.getTenantId());
                building1.setUnitNumber(unitNumber);
                building1.setHouseNumber(houseNumber);
            }
        }
        return buildingList;
    }

    @Override
    public Integer selectBuildingByBuildingNumber(String estateId, String delFlag, String tenantId) {
        return buildingMapper.selectBuildingByBuildingNumber(estateId, delFlag, tenantId);
    }

    @Override
    public List<Building> selectBuildingByEstateId(String estateId, String delFlag) {
        return buildingMapper.selectBuildingByEstateId(estateId, delFlag);
    }

    @Override
    public List<Node> selectBuildingLevelList(Building building) {
        return buildingMapper.selectBuildingLevelList(building);
    }

    @Override
    @Transactional
    public int editBuilding(Building building, Long userId) {
        Building byBuildingId = buildingMapper.selectBuildingByBuildingId(building.getBuildingId());
        if (!TenantContext.getTenantId().equals(byBuildingId.getTenantId())) {
            return 0;
        }

        Building sqlBuilding = buildingMapper.selectBuildingByEstateIdAndBuildingName(building.getEstateId(), building.getBuildingName(), TenantContext.getTenantId());
        if (ObjectUtil.isNotEmpty(sqlBuilding)) {
            if (!sqlBuilding.getBuildingId().equals(building.getBuildingId())) {
                throw new ServiceException("该楼栋名称已存在");
            }
        }

        List<Unit> unitList = building.getUnitList();
        if (CollectionUtil.isNotEmpty(unitList)) {
            for (Unit unit : unitList) {

                Unit sqlUnit = iUnitService.selectUnitByUnitBuildingAndUnitName(building.getBuildingId(), unit.getUnitName());
                if (ObjectUtil.isNotEmpty(sqlUnit)) {
                    if (!sqlUnit.getUnitId().equals(unit.getUnitId())) {
                        throw new ServiceException(unit.getUnitName() + "单元名称已存在");
                    }
                }

                if (unit.getUnitId() != null) {
                    unit.setUpdateTime(DateUtils.getNowDate());
                    iUnitService.updateUnit(unit);
                } else {
                    unit.setBuildingId(building.getBuildingId());
                    unit.setTenantId(TenantContext.getTenantId());
                    unit.setOperatorId(userId);
                    iUnitService.insertUnit(unit);
                }
            }
        }
        building.setUpdateTime(DateUtils.getNowDate());
        return buildingMapper.updateBuilding(building);
    }

    @Override
    @Transactional
    public String importUser(List<Building> buildingList, String username, Long userId) {
        if (StringUtils.isNull(buildingList) || buildingList.size() == 0) {
            throw new ServiceException("导入用户数据不能为空！");
        }

        for (Building building : buildingList) {
            if (building.getFloors() == null) {
                throw new ServiceException("格式有误，层数必须为数字");
            }
            Estate estate = iEstateService.selectEstateByEstateName(building.getEstateName(),TenantContext.getTenantId());
            if (ObjectUtil.isEmpty(estate)) {
                throw new ServiceException(building.getEstateName() + "楼盘不存在，请检查");
            }
            if (building.getBuildingName().length() > 10) {
                throw new ServiceException("楼栋名称不能超过10个字");
            }
            Building sqlBuilding = buildingMapper.selectBuildingByEstateIdAndBuildingName(building.getEstateId(), building.getBuildingName(), null);
            if (ObjectUtil.isEmpty(sqlBuilding)) {
                building.setEstateType(estate.getEstateType());
                building.setPremisesAddress(estate.getPremisesAddress());
                building.setPropertyId(estate.getPropertyId());
                building.setPropertyName(estate.getPropertyName());
                building.setProvinceId(estate.getProvinceId());
                building.setCityId(estate.getCityId());
                building.setDistrictId(estate.getDistrictId());
                building.setStreetId(estate.getStreetId());
                building.setCommunityId(estate.getCommunityId());
                building.setTenantId(TenantContext.getTenantId());
                building.setCreateTime(DateUtils.getNowDate());
                building.setOperatorId(userId);
                building.setEstateId(estate.getEstateId());
                buildingMapper.insertBuilding(building);

                insertUnit(userId, building);
            } else {
                Unit sqlUnit = iUnitService.selectUnitByUnitBuildingAndUnitName(sqlBuilding.getBuildingId(), building.getUnitName());
                if (ObjectUtil.isNotEmpty(sqlUnit)) {
                    throw new ServiceException(building.getUnitName() + "单元名称已存在");
                }
                insertUnit(userId, sqlBuilding);
            }

        }
        return "导入成功";
    }

    private void insertUnit(Long userId, Building building) {
        Unit unit = new Unit();
        unit.setOperatorId(userId);
        unit.setBuildingId(building.getBuildingId());
        unit.setCreateTime(DateUtils.getNowDate());
        unit.setTenantId(TenantContext.getTenantId());
        unit.setUnitName(building.getUnitName());
        unit.setFloors(building.getFloors());
        iUnitService.insertUnit(unit);
    }
}
